package com.example.video.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @deprecated
 */
@Component
@Slf4j
public class VideoUtil {

    @Value("${downLoadPath}")
    private String downloadPath;

    public void downloadVideo( String userName, String date, String videoId, String videoUrl) {
        String savePath = downloadPath+ "/"+ userName +"/" +date + "/" + videoId + ".mp4"; // 视频保存的路径

        try {
            File directory = new File(downloadPath+userName+"/"+ date);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 创建 URL 对象
            URL url = new URL(videoUrl);
            // 打开连接
            URLConnection connection = url.openConnection();
            // 获取输入流
            InputStream inputStream = connection.getInputStream();
            // 创建输出流
            FileOutputStream outputStream = new FileOutputStream(savePath);

            // 读取数据并写入文件
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            outputStream.close();
            inputStream.close();

            log.info("视频下载完成！");
        } catch (Exception e) {
            log.info("视频下载失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
